<?php
namespace app\epiiadmin\controller;

use think\Db;
use think\facade\Config;
use think\facade\Env;
use wslibs\i\epiiadmin\ILeftAndTopData;

/**
 * Created by PhpStorm.
 * User: mrren
 * Date: 2018/6/29
 * Time: 上午10:43
 */
class EpiiController extends \think\Controller
{
    private $page_title = "";
    public function setPageTitle($title)
    {
        $this->page_title = $title;
    }
    public function fetchNoLayout($template = '', $vars = [], $config = [])
    {
        $this->assign("title", ($this->page_title?($this->page_title."-"):Config::get("app_name")));
        $this->view->engine->layout(false);
        return parent::fetch($template, $vars, $config);
    }

    public function fetch($template = '', $vars = [], $config = [])
    {
        $this->assign("title", ($this->page_title?($this->page_title."-"):Config::get("app_name")));
        return parent::fetch($template, $vars, $config); // TODO: Change the autogenerated stub
    }

    public function jsArgs($dataOrKey = null, $value = null)
    {
        if ($dataOrKey == null) {
            return $this->app->js_args;
        }
        if (is_string($dataOrKey)) {
            if (is_null($value)) {
                return $this->app->js_args[$dataOrKey];
            } else {
                $this->app->js_args[$dataOrKey] = $value;
            }
        }
        if (is_array($dataOrKey)) {
            $this->app->js_args->setData($dataOrKey);
        }
        return $this->app->js_args;
    }

    public function jsAppName($pathtoname = null)
    {
        return $this->jsArgs("appName", $pathtoname);
    }

    /**
     * @param ILeftAndTopData $dataProvider
     * @return mixed
     */
    public function showTopWindow(ILeftAndTopData $dataProvider)
    {
        bind("wslibs\\i\\epiiadmin\\ILeftAndTopData", $dataProvider);//,//需要用户自行修改)

        Config::set("app_theme", $dataProvider->getTheme());
        Config::set("app_left_theme", $dataProvider->getLeftMenuTheme());
        $this->jsArgs("isTop", 1);
        return $this->fetchNoLayout("epiiadmin@index/index");
    }

    public function tableJsonData($table_name_or_query,$where,callable $row_callback = null,callable $callback = null)
    {
        $query_count = null;
        if(is_string($table_name_or_query))
        {
            $query = Db::name($table_name_or_query);
            $query_count = Db::name($table_name_or_query);
            $query->order("id desc");
        }else{
            $query = $table_name_or_query;
            $query_count =clone $table_name_or_query;
        }
        $count =$query_count->where($where)->count();
        $list = $query->where($where)->limit($this->request->param("offset"),$this->request->param("limit"))->select();
        $outdata = ["rows" =>$row_callback?array_map($row_callback,$list):$list, "total" => $count];
        if ($callback)
        {
            $outdata['rows' ] = $callback($outdata['rows']);
        }
        return json($outdata);
    }




}